package com.zhuhjay.utils;

import cn.hutool.core.util.BooleanUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author ZhuHJay
 * @date 2023/1/12 19:06
 */
public class RedisUtils {

    private static final StringRedisTemplate TEMPLATE;
    static {
        TEMPLATE = SpringContextHolder.getBean(StringRedisTemplate.class);
    }

    /**
     * 尝试获取锁，并且给锁加上过期时间
     * @param lock key lock
     * @param expire 过期时间
     * @param timeUnit 单位
     * @return 是否获取锁
     */
    public static boolean tryLock(String lock, long expire, TimeUnit timeUnit) {
        Boolean aBoolean = TEMPLATE.opsForValue().setIfAbsent(lock, "1", expire, timeUnit);
        return BooleanUtil.isTrue(aBoolean);
    }

    /**
     * 释放锁
     * @param lock key lock
     * @return 是否释放锁
     */
    public static boolean unLock(String lock) {
        return BooleanUtil.isTrue(TEMPLATE.delete(lock));
    }

}
